import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useUserStore } from '@/stores/user'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// Token刷新标志位
let isRefreshing = false
// 待重试请求队列
let requestQueue = []

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 处理文件下载（blob类型）
    if (response.config.responseType === 'blob') {
      return response.data
    }
    
    const res = response.data
    
    // 如果响应成功，直接返回数据
    if (res.code === 200) {
      return res
    }
    
    // 处理业务错误
    if (res.code === 401) {
      // 如果不在登录页或注册页，才显示提示
      const currentPath = router.currentRoute.value.path
      if (currentPath !== '/login' && currentPath !== '/register') {
        ElMessage.error('登录已过期，请重新登录')
      }
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('roles')
      localStorage.removeItem('permissions')
      localStorage.removeItem('menus')
      if (currentPath !== '/login' && currentPath !== '/register') {
        router.push('/login')
      }
      return Promise.reject(new Error(res.message || '未授权'))
    }
    
    // 其他错误
    ElMessage.error(res.message || '请求失败')
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  async error => {
    console.error('响应错误:', error)
    
    if (error.response) {
      const status = error.response.status
      const config = error.config
      
      const currentPath = router.currentRoute.value.path
      const isAuthPage = currentPath === '/login' || currentPath === '/register'
      
      // 处理blob类型的错误响应
      if (error.response.data instanceof Blob && error.response.config.responseType === 'blob') {
        try {
          const text = await error.response.data.text()
          const data = JSON.parse(text)
          if (data.message) {
            ElMessage.error(data.message)
          }
        } catch (e) {
          console.error('解析blob错误:', e)
        }
      }
      
      // 处理401错误，尝试刷新Token
      if (status === 401 && !config._retry) {
        // 如果正在刷新Token，将请求加入队列
        if (isRefreshing) {
          return new Promise((resolve) => {
            requestQueue.push(() => {
              config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`
              resolve(request(config))
            })
          })
        }
        
        config._retry = true
        isRefreshing = true
        
        try {
          // 尝试刷新Token
          const userStore = useUserStore()
          const success = await userStore.refreshAccessToken()
          
          if (success) {
            // Token刷新成功，重试所有队列中的请求
            requestQueue.forEach(callback => callback())
            requestQueue = []
            
            // 重试当前请求
            config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`
            return request(config)
          }
        } catch (refreshError) {
          console.error('Token刷新失败:', refreshError)
          // Token刷新失败，清空队列
          requestQueue = []
          if (!isAuthPage) {
            router.push('/login')
          }
          return Promise.reject(refreshError)
        } finally {
          isRefreshing = false
        }
      }
      
      // 处理其他错误
      switch (status) {
        case 401:
          if (!isAuthPage) {
            ElMessage.error('登录已过期，请重新登录')
            localStorage.clear()
            router.push('/login')
          }
          break
        case 403:
          if (!isAuthPage) {
            ElMessage.error('没有访问权限')
          }
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器错误')
          break
        default:
          ElMessage.error(error.response.data.message || '请求失败')
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查您的网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

export default request